package com.example.config;

import cn.itcast.pojo.Country;
import cn.itcast.pojo.Province;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CommonConfig {

    // 通过@Bean注入Country 对象
    // 如果配置文件中配置了指定的信息 则注入 否则不注入
    @ConditionalOnProperty(prefix = "country", name = {"name", "system"})
    @Bean
    public Country country(@Value("${country.name}") String name, @Value("${country.system}") String system) {
        Country country = new Country();
        country.setName(name);
        country.setSystem(system);
        return country;
    }

    //@Bean("aa")  给bean起名

    // 若方法内部需要使用到ioc容器中的已经存在的bean对象
    // 那么只需要在方法上声明即可
    // spring会自动注入

    // 若ioc容器中不存在Country 则注入Province 否则不注入
    //@Bean
    //@ConditionalOnMissingBean(Country.class)


    //若有DispatcherServlet 则注入Province
    @Bean
    @ConditionalOnClass(name = "org.springframework.web.servlet.DispatcherServlet")
    public Province province() {
        return new Province();
    }
}
